﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DGSFramework;
using System.Web.Security;
using ActiveUp.Net.Mail;
using OpenPop.Pop3;
using System.Net;
using System.Net.Mail;
using System.Xml.Linq;

namespace Framework
{
    public partial class Register : System.Web.UI.Page
    {
        DGSFrameworkEntities entity = new DGSFrameworkEntities();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //LoadProfile();
            }
        }

        protected void btnFinishRegister_ServerClick(object sender, EventArgs e)
        {
            try
            {
                string UserName = tbUserName.Value.Trim();
                string uEmail = tbEmail.Value.Trim();
                var mem = entity.udv_Users.Where(m => m.UserName == UserName).FirstOrDefault();
                MembershipUser someUser = Membership.GetUser(UserName);
                if (someUser == null)
                {
                    //insert to asp_membership
                    MembershipCreateStatus status;
                    MembershipUser memberShipUser = Membership.CreateUser(tbUserName.Value.Trim(), tbPassword.Value, tbEmail.Value.Trim(),"yes","yes",false, out status);
                    if (memberShipUser != null)
                    {
                        AddUser(memberShipUser);

                        //insert to udv_orders
                        AddtoOder();


                        //send mail
                        SendEmail();



                        //CleanImageUploadTemp();
                        //data cache
                        Cache.Remove("User");
                        Response.Redirect("/Success.aspx");
                        Session["objMember"] = null;
                    }
                    

                }
                else
                {
                    lblAlert.Text = "Đăng ký không thành công !. Tài khoản đang sử dụng.";
                }
            }
            catch (Exception)
            {
                lblAlert.Text = "Đăng ký không thành công !";
            }
            
            
        }
        private bool SendEmail()
        {
            udv_EmailHostSetting emailHostSetting = entity.udv_EmailHostSetting.OrderByDescending(es => es.EmailHostSettingID).FirstOrDefault();
            string serverMail = emailHostSetting.ServerMailSMTP.Trim();
            string port = emailHostSetting.PortMailSMTP.ToString();
            string yourMailAccount = emailHostSetting.MailAccount.Trim();
            string yourMailPassword = Globals.Base64Decode(emailHostSetting.Password.Trim());

            SendMail sm = new SendMail();
            sm.ServerMail = serverMail;
            sm.ServerPort = port;
            sm.SSL = emailHostSetting.SSL.Value;
            sm.YourMailAccount = yourMailAccount;
            sm.YourMailPassword = yourMailPassword;
            sm.SetUpYourServerMail();

            string receive = yourMailAccount;

            XDocument xDocContact = XDocument.Load(Server.MapPath(ConfigPaths.Path_ContactGroup_Xml));
            var listXEContact = xDocContact.Descendants("contact_group")
                .Select(cg => new
                {
                    ID = cg.Element("id").Value.Trim(),
                    Mail = cg.Element("mail").Value.Trim(),
                    ShowName = cg.Element("showname").Value.Trim(),
                    ShowName_en = cg.Element("showname").Value.Trim(),
                    Index = cg.Element("index").Value.Trim(),
                    Group = cg.Element("group").Value.Trim()
                })
                .ToList();
            foreach (var item in listXEContact)
            {
                receive += item.Mail + ",";
            }
            string pMethod = string.Empty;
            if (Request.Form["rdPayMethod"] != null)
            {
                pMethod = Request.Form["rdPayMethod"];
            }
            int pID = 0;
            if (Request.Form["rdPlan"] != null)
            {
                pID = Convert.ToInt32(Request.Form["rdPlan"]);
            }
            var product = entity.udv_Products.Where(p => p.ProductID == pID).FirstOrDefault();
            string title = "Thông tin đăng ký sử dụng sản phẩm 3W";
            string uEmail = tbEmail.Value.Trim();
            string body = "<table><thead style='background: #4dcc00'><tr><td colspan='2'><img src='http://3wco.vn/Images/Signature150903.png' style='max-width: 100%' /></td></tr><tr><td colspan='2'><h3>THÔNG TIN ĐĂNG KÝ</h3><td></tr></thead>";
            body += "<tbody>";
            body += "<tr style='background: #ccc'><td colspan='2'>Thông tin cá nhân</td></tr>";
            body += "<tr><td>Họ và tên :</td><td>"+ tbLastName.Value + " " + tbFirstName.Value +"</td><tr>";
            body += "<tr><td>So CMND : </td><td>"+ tbPersonID.Value +"</td></tr>";
            body += "<tr><td>Địa chỉ : </td><td>"+ tbAdress.Value +"</td></tr>";
            body += "<tr><td>Số điện thoại : </td><td>" + tbPhone.Value + "</td></tr>";
            body += "<tr><td>Email : </td><td>" + tbEmail.Value + "</td></tr>";
            body += "<tr><td>Thông tin chuyển khoản : </td><td>" + pMethod + "</td></tr>";
            body += "<tr style='background: #ccc'><td colspan='2'>Thông tin tài khoản</td></tr>";
            body += "<tr><td>User name : </td><td>" + tbUserName.Value + "</td></tr>";
            body += "<tr><td style='background: #ccc'>Thông tin gói sản phẩm </td></tr>";
            body += "<tr><td>"+ product.Title +"</td><td>" + product.Summary + "</td><tr>";
            body += "<tr><td>Giá : </td><td>"+ string.Format("{0:N}", product.UnitPrice) + "</td></tr>";
            body += "</tbody>";
            body += "</table>";
            body += "<hr />";
            body += "<p>Số tài khoản : 0000000 - Ngân hàng thương mại cổ phần Á Châu ACB</p>";
            body += "<p>Địa chỉ thanh toán bằng tiền mặt: 248-250 Nguyen Dinh Chieu, Ward 6, Dist 3, HCMC, Vietnam. Hotline: +84 906 870 228 </p>";
            sm.CreateMailObject(uEmail, body, title, emailHostSetting.MailReceive);
            if (sm.MailSending())
            {
                return true;

            }
            return true;
        }
        public void AddtoOder()
        {
            try
            {
                string pMethod = string.Empty;
                int pID = 0;
                udv_Orders newOrder = new udv_Orders();
                udv_OrderDetails newOrderDetail = new udv_OrderDetails();
                if (Request.Form["rdPlan"] != null)
                {
                     pID = Convert.ToInt32(Request.Form["rdPlan"]);
                }
                if (Request.Form["rdPayMethod"] != null)
                {
                     pMethod = Request.Form["rdPayMethod"];
                }
                string pDes = tbDes.Value;

                // insert to udv_Orders
                newOrder.AddedDate = DateTime.Now;
                newOrder.RequireDate = DateTime.Now;
                newOrder.Address = tbAdress.Value;
                newOrder.Tel = tbPhone.Value;
                newOrder.Email = tbEmail.Value;
                newOrder.PayMethod = pMethod;
                newOrder.Status = 0;                
                newOrder.ViewStatus = false;
                newOrder.ReplyStatus = false;
                newOrder.ExpiredDate = DateTime.Now;
                newOrder.Description = pDes;
                if (Session["objMember"] != null)
                {
                    var lstUser = Session["objMember"] as udv_Users;
                    var user = entity.aspnet_Users.Where(d => d.UserId == lstUser.UserID).FirstOrDefault();
                    newOrder.aspnet_Users = user;
                }
                var product = entity.udv_Products.Where(p => p.ProductID == pID).FirstOrDefault();
                newOrder.Receiver = tbLastName.Value + " " + tbFirstName.Value;
                newOrder.Amount = product.UnitPrice;
                entity.AddToudv_Orders(newOrder);
                entity.SaveChanges();

                //insert to udv_OrderDetails              
                newOrderDetail.udv_Orders = newOrder;
                newOrderDetail.udv_Products = product;
                newOrderDetail.UnitPrice = product.UnitPrice;
                newOrderDetail.Quantity = 1;
                newOrderDetail.PromotionPrice = 0;
                newOrderDetail.SalePrice = 0;
                newOrderDetail.PromotionPercent = 0;
                entity.AddToudv_OrderDetails(newOrderDetail);
                entity.SaveChanges();
            }
            catch (Exception)
            {
                throw;
            }
        }
        private void AddUser(MembershipUser memberShipUser)
        {
            string pID = string.Empty;
            string[] rolePlanA = new string[] { "Plan A" };
            string[] roleU = new string[] { "User" };
            if (Request.Form["rdPlan"] != null)
            {
                pID = Request.Form["rdPlan"];
            }
            if (pID == "1")
            {
                Roles.AddUserToRoles(memberShipUser.UserName, rolePlanA);

            }else
            {
                Roles.AddUserToRoles(memberShipUser.UserName, roleU);
            }
            udv_Users newUser = new udv_Users();
            newUser.aspnet_Users = entity.aspnet_Users.Where(au => au.UserName == memberShipUser.UserName).FirstOrDefault();
            newUser.UserName = memberShipUser.UserName;
            newUser.Email = tbEmail.Value.Trim();
            newUser.FirstName = tbFirstName.Value.Trim();
            newUser.LastName = tbLastName.Value.Trim();
            newUser.Phone = tbPhone.Value.Trim();
            newUser.AddedDate = DateTime.Now;
            newUser.AddedBy = "User";
            newUser.IsActive = false;
            newUser.Visible = true;
            newUser.PersonID = Int32.Parse(tbPersonID.Value);
            newUser.ImageUrl = "";            
            newUser.ExpiredDate = DateTime.Now;
            entity.AddToudv_Users(newUser);
            entity.SaveChanges();
            var getmem = entity.udv_Users.Where(a => a.UserName == newUser.UserName).FirstOrDefault();
            if (getmem != null)
            {
                Session["objMember"] = getmem;
            }
        }
        public void CreateDBLog(int? postID, int? postCateID, TypeAction typeAction, string title, string _abstract, string description,
       string releaseDate, string expireDate, string isApproved, string statusID, string metaDescription, string metaKeywords)
        {
            udv_Log log = new udv_Log();
            log.PostID = postID;
            log.PostCateID = postCateID;
            log.TypeAction = (int)typeAction;
            log.Title = title;
            log.Abstract = _abstract;
            log.Description = description;
            log.ReleaseDate = releaseDate;
            log.ExpireDate = expireDate;
            log.IsApproved = isApproved;
            log.StatusID = statusID;
            log.MetaDescription = metaDescription;
            log.MetaKeywords = metaKeywords;
            log.ActionedDate = DateTime.Now;
            log.ActionBy = Membership.GetUser().UserName;
            log.IpAdress = Globals.GetClientIPAddress();

            entity.AddToudv_Log(log);
            entity.SaveChanges();
        }

        //public void LoadProfile()
        //{
        //    if (Session["objMember"] != null)
        //    {
        //        var objU = Session["objMember"] as udv_Users;
        //        string uName = objU.UserName;
        //        MembershipUser someUser = Membership.GetUser(uName);
        //        udv_Users user = entity.udv_Users.Where(us => us.UserName == someUser.UserName).FirstOrDefault();
        //        tbPersonID.Value = user.PersonID.ToString();
        //        tbLastName.Value = user.LastName;
        //        tbFirstName.Value = user.FirstName;
        //        tbAdress.Value = user.Address;
        //        tbPhone.Value = user.Phone;
        //    }

        //}

    }
}